package com.aifast.core.dataScope;

import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.ObjectUtil;
import com.aifast.common.global.Const;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.operators.conditional.AndExpression;
import net.sf.jsqlparser.expression.operators.relational.EqualsTo;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.parser.CCJSqlParserManager;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.select.FromItem;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;

import java.io.StringReader;

/**
 * @Author fujian
 * @since 2022/9/7 15:20
 */
public class AbstractDataScopeHandler {

    final static String ONLY_ME_SQl = "user_id = {}";
    final static String fujian_SQl = "id = 0";
    final static String ONLY_ME_SQl2 = "find_in_set({},{})";
    final static String CURRENT_ORG_SQl = "org_id = {}";
    final static String CURRENT_AND_CHILD_ORG_SQl = "org_id IN ( SELECT id FROM sys_org WHERE deleted is false and ( id = {} or find_in_set( {} , pids ) ))";
    final static String CURRENT_AND_CHILD_ORG_SQl2 = "SELECT id FROM sys_org WHERE deleted is false and ( id = {} or find_in_set( {} , pids ) )";
    final static String CUSTOM_SQl = "org_id IN ({})";
    final static String USERID = "user_id";
    final static String ORGID = "org_id";
    final static String SYSBOL = "||";

    protected static boolean isNotNull(StrBuilder stringBuilder){
        return !stringBuilder.isEmpty();
    }

    /**
     * 获取带别名的列
     *
     * @param table      表
     * @param columnName 列名
     * @return 新的列名
     */
    protected static Column getAliasColumn(Table table, String columnName) {
        StringBuilder column = new StringBuilder();
        if (table.getAlias() != null) {
            column.append(table.getAlias().getName()).append(".");
        }
        column.append(columnName);
        return new Column(column.toString());
    }

    /**
     * 获取表别名字符串 没有则返回空
     *
     * @param table
     * @return
     */
    protected static String getTableAlias(Table table) {
        return ObjectUtil.isNotNull(table.getAlias()) ? table.getAlias().getName() + "." : Const.EMPTY;
    }

    /**
     * 构建 = 语句
     *
     * @param select
     * @param column
     * @param value
     */
    protected static EqualsTo buildEqualsToSql(PlainSelect select, String column, Expression value) {

        FromItem fromItem = select.getFromItem();
        Column aliasColumn = getAliasColumn((Table) fromItem, column);
        Expression where = select.getWhere();
        EqualsTo equalsTo = new EqualsTo();

        equalsTo.setLeftExpression(aliasColumn);
        equalsTo.setRightExpression(value);
        /*if (ObjectUtil.isNull(where)) {
            select.setWhere(equalsTo);
        } else {
            select.setWhere(where instanceof OrExpression ? new AndExpression(new Parenthesis(where), equalsTo) : new AndExpression(where, equalsTo));
        }*/

        return equalsTo;
    }

    /**
     * 构建 in 语句
     * @param select
     * @param column
     * @param value
     */
    protected static InExpression buildInSql(PlainSelect select, String column, ExpressionList value) {
        FromItem fromItem = select.getFromItem();
        Column aliasColumn = getAliasColumn((Table) fromItem, column);
        Expression where = select.getWhere();
        InExpression inExpression = new InExpression(aliasColumn, value);
        /*if (ObjectUtil.isNull(where)) {
            select.setWhere(inExpression);
        } else {
            select.setWhere(where instanceof OrExpression ? new AndExpression(new Parenthesis(where), inExpression) : new AndExpression(where, inExpression));
        }*/

        return inExpression;
    }


    private static String getSql(String originalSql,String dataSql) throws JSQLParserException {
        //使用sql解析工具进行拼接
        CCJSqlParserManager manager = new CCJSqlParserManager();
        Select parse = (Select)manager.parse(new StringReader(originalSql));
        PlainSelect selectBody = (PlainSelect)parse.getSelectBody();
        Expression where = selectBody.getWhere();
        Expression parseCondExpression = CCJSqlParserUtil.parseCondExpression(dataSql);
        /*判断源sql是否有where条件*/
        if(ObjectUtil.isNotNull(where)){
            selectBody.setWhere(new AndExpression(where, parseCondExpression));
        }else {
            selectBody.setWhere(parseCondExpression);
        }
        return selectBody.toString();
    }

}
